package com.jic.point.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.jic.common.base.vo.AdminOperate;
import com.jic.common.base.vo.RestResult;
import com.jic.point.constant.consist.ResponseCode;
import com.jic.point.model.entity.ConfActivityRule;
import com.jic.point.model.entity.ConfActivityRuleApply;
import com.jic.point.model.entity.ConfActivityRuleDetail;
import com.jic.point.model.vo.request.ConfActivityRuleRequest;
import com.jic.point.model.vo.request.ConfThirdPartRequest;
import com.jic.point.model.vo.response.ConfActivityRuleResponse;
import com.jic.point.service.ConfActivityRuleApplyService;
import com.jic.point.service.ConfActivityRuleDetailService;
import com.jic.point.service.ConfActivityRuleService;
import com.jic.point.service.ConfPlatformService;
import com.jic.point.utils.DateUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: tzc
 * @date: 2020-10-11 17:28:32
 */
@RestController
@Slf4j
@RequestMapping("/confActivityRule")
@Api(tags = " [活动规则主表]控制类-PC")
public class ConfActivityRuleController {
    @Autowired
    private ConfActivityRuleService service;
    @Autowired
    private ConfActivityRuleApplyService serviceApply;
    @Autowired
    private ConfActivityRuleApplyService confActivityRuleApplyService;
    @Resource
    private ConfPlatformService confPlatformService;
    @Resource
    private ConfActivityRuleDetailService confActivityRuleDetailService;

    /**
     * 新增记录
     *
     * @param request 新增[活动规则主表]请求参数
     * @return ConfActivityRuleResponse 新增[活动规则主表]响应参数
     * author tzc
     * @date 2020-3-11 20:54:04
     */
    @ApiOperation(value = "新增[活动规则主表]记录")
    @PostMapping("/save")
    @ResponseBody
    public RestResult<Long> save(@RequestBody ConfActivityRuleRequest request) throws Throwable {
        ConfActivityRule confActivityRule = new ConfActivityRule();
        BeanUtils.copyProperties(request, confActivityRule);
        long flag = service.save(confActivityRule);
        return RestResult.success(flag);
    }

    /**
     * 新增或修改记录
     *
     * @param
     * @return ConfActivityRuleResponse 新增或修改[活动规则主表]响应参数
     * author tzc
     * @date 2020-3-11 20:54:04
     */
    @ApiOperation(value = "保存或更新[活动规则主表]")
    @PostMapping("/saveOrUpdate")
    @ResponseBody
    @Transactional
    public RestResult<Long> saveOrUpdate(@RequestBody Map map) throws Throwable {
        ConfActivityRule confActivityRule = JSON.parseObject(JSON.toJSONString(map.get("dataForm")), ConfActivityRule.class);
        //组装活动规则主表数据
        Map adminOperate = (Map) map.get("adminOperate");
        confActivityRule.setDeptId(Long.parseLong(adminOperate.get("deptId").toString()));
        confActivityRule.setCode(confActivityRule.getPlatformCode() + DateUtils.format(new Date(), "yyyyMMddHHmmssSSS"));
        confActivityRule.setLimited(confActivityRule.getTotal());
        confActivityRule.setAvailable(confActivityRule.getTotal());
        confActivityRule.setCurrentAction(0);
        confActivityRule.setOutRuleKey("HD" + confActivityRule.getPlatformCode() + DateUtils.format(new Date(), "yyyyMMddHHmmssSSS"));
        confActivityRule.setAuditSts(0);
        confActivityRule.setSts(1);
        confActivityRule.setCreateTime(new Date());
        confActivityRule.setCreator(Long.parseLong(adminOperate.get("operator").toString()));
        confActivityRule.setAdminOperate(JSON.parseObject(JSON.toJSONString(map.get("adminOperate")), AdminOperate.class));
        //插入活动表之前进行积分冻结
        int i = confPlatformService.activityRuleDeductionPoints(confActivityRule);
        if (i < 1) return RestResult.error("0111", "生成活动，积分扣除失败！活动添加失败！");
        //积分冻结成功，插入积分表中
        service.insertActiveRuleLog(confActivityRule);
        //积分冻结插入平台流水表中
        confPlatformService.insertPlatFromLog(confActivityRule);
        //插入至活动表
        long flag = service.saveOrUpdate(confActivityRule);
        //组装基本规则表
        List<Map> dataForm2 = (List<Map>) JSONArray.parse(map.get("dataForm2").toString());
        List<Map> ltemp = new ArrayList<>();
        for (Map o : dataForm2) {
            List<Map> list = (List<Map>) o.get("list");
            list.forEach(item -> {
                Map mm = new HashMap();
                mm.put("rulesId", confActivityRule.getId());
                mm.put("templateId", o.get("id"));
                mm.put("sceneName", o.get("sceneName"));
                mm.put("sceneId", o.get("sceneId"));
                mm.put("deptId", Long.parseLong(adminOperate.get("deptId").toString()));
                mm.put("startTime", confActivityRule.getStartTime());
                mm.put("endTime", confActivityRule.getEndTime());
                mm.put("deleteFlag", 0);
                mm.put("platformCode", confActivityRule.getPlatformCode());
                for (Object key : item.keySet()) {
                    mm.put(key, item.get(key));
                }
                ltemp.add(mm);
            });
        }
        //添加规则
        int j = confActivityRuleDetailService.saveListDetail(ltemp);

        return RestResult.success(flag);
    }

    @ApiOperation(value = "活动规则主表修改数据")
    @PostMapping("/ruleUpdate")
    @ResponseBody
    public RestResult<Long> ruleUpdate(@RequestBody Map map) {
        ConfActivityRule confActivityRule = JSON.parseObject(JSON.toJSONString(map.get("dataForm")), ConfActivityRule.class);

        long flag = service.saveOrUpdate(confActivityRule);

        //组装基本规则表
        Map adminOperate = (Map) map.get("adminOperate");
        List<Map> dataForm2 = (List<Map>) JSONArray.parse(map.get("dataForm2").toString());
        List<Map> ltemp = new ArrayList<>();
        for (Map o : dataForm2) {
            List<Map> list = (List<Map>) o.get("list");
            list.forEach(item -> {
                Map mm = new HashMap();
                mm.put("rulesId", confActivityRule.getId());
                mm.put("templateId", o.get("id"));
                mm.put("sceneName", o.get("sceneName"));
                mm.put("sceneId", o.get("sceneId"));
                mm.put("deptId", Long.parseLong(adminOperate.get("deptId").toString()));
                mm.put("startTime", confActivityRule.getStartTime());
                mm.put("endTime", confActivityRule.getEndTime());
                mm.put("deleteFlag", 0);
                mm.put("platformCode", confActivityRule.getPlatformCode());
                for (Object key : item.keySet()) {
                    mm.put(key, item.get(key));
                }
                // ltemp.add(mm);
                //修改
                confActivityRuleDetailService.saveOrUpdate(JSON.parseObject(JSON.toJSONString(mm), ConfActivityRuleDetail.class));
            });
        }

        return RestResult.success(flag);
    }

    /**
     * 删除记录
     *
     * @param request 删除[活动规则主表]请求参数
     * @return ConfActivityRuleResponse 删除[活动规则主表]响应参数
     * author tzc
     * @date 2020-3-11 20:54:04
     */
    @ApiOperation(value = "删除[活动规则主表]记录")
    @PostMapping("/delete")
    @ResponseBody
    public RestResult<Long> delete(@RequestBody ConfActivityRuleRequest request) throws Throwable {
        ConfActivityRule confActivityRule = new ConfActivityRule();
        BeanUtils.copyProperties(request, confActivityRule);
        long flag = service.deleteByPrimaryKeyLogically(confActivityRule);
        return RestResult.success(flag);
    }

    /**
     * 修改记录
     *
     * @param request 修改[活动规则主表]请求参数
     * @return ConfActivityRuleResponse 修改[活动规则主表]响应参数
     * author tzc
     * @date 2020-3-11 20:54:04
     */
    @ApiOperation(value = "修改[活动规则主表]记录")
    @PostMapping("/update")
    @ResponseBody
    public RestResult<Long> update(@RequestBody ConfActivityRuleRequest request) throws Throwable {
        ConfActivityRule confActivityRule = new ConfActivityRule();
        BeanUtils.copyProperties(request, confActivityRule);
        long flag = service.updateByPrimaryKeySelective(confActivityRule);
        return RestResult.success(flag);
    }

    /**
     * 单表查询详情信息
     *
     * @param request 查询[活动规则主表]详情请求参数
     * @return ConfActivityRuleResponse 查询[活动规则主表]详情响应参数
     * author tzc
     * @date 2020-3-11 20:54:04
     */
    @PostMapping("/getByPrimaryKey")
    @ApiOperation(value = "查询[活动规则主表]详情")
    @ResponseBody
    public RestResult<Map> getByPrimaryKey(@Validated @RequestBody ConfActivityRuleRequest request) {
        log.info("查询详情请求参数入参，{}", JSONObject.toJSONString(request));
        if (request != null && request.getId() != null) {

            ConfActivityRule confActivityRule = new ConfActivityRule();
            BeanUtils.copyProperties(request, confActivityRule);
            ConfActivityRule result = service.getByPrimaryKey(confActivityRule);
            log.info("查询详情请求参数出参，{}", JSONObject.toJSONString(result));
            if (result == null) {
                return RestResult.error(ResponseCode.EXCEPTION, "记录不存在");
            }
            ConfActivityRuleApply confActivityRuleApply = new ConfActivityRuleApply();
            BeanUtils.copyProperties(result, confActivityRuleApply);
            List<ConfActivityRuleDetail> list = service.selDetailList(confActivityRuleApply);
            ConfActivityRuleResponse bo = new ConfActivityRuleResponse();
            BeanUtils.copyProperties(result, bo);
            Set<Long> collect = list.stream().map(ConfActivityRuleDetail::getSceneId).collect(Collectors.toSet());
            Set<String> collects = new HashSet<>();
            collect.forEach(item -> {
                collects.add(item.toString());
            });
            Map<Long, List<ConfActivityRuleDetail>> collect1 = list.stream().collect(Collectors.groupingBy(ConfActivityRuleDetail::getSceneId));

            List l = new ArrayList();
            for (Long key : collect1.keySet()) {
                List<ConfActivityRuleDetail> confActivityRuleDetails = collect1.get(key);
                Map map = new HashMap<>();
                map.put("sceneId", confActivityRuleDetails.get(0).getSceneId());
                map.put("sceneName", confActivityRuleDetails.get(0).getSceneName());
                map.put("list", confActivityRuleDetails);
                l.add(map);
            }


            Map m = new HashMap();
            m.put("detailList", l);
            m.put("rule", bo);
            m.put("sceneId", collects);
            return RestResult.success(m);
        }
        log.info("查询详情请求结束");
        return RestResult.success(new HashMap());
    }

    /**
     * 分页查询
     *
     * @param request 分页查询请求参数
     * @return 分页列表
     * @throws Throwable 业务异常和系统异常
     */
    @PostMapping("/listPage")
    @ApiOperation(value = " 分页查询列表 ")
    @ResponseBody
    public RestResult<PageInfo<ConfActivityRule>> listPage(@RequestBody ConfActivityRuleRequest request) throws Throwable {
        ConfActivityRule param = new ConfActivityRule();
        BeanUtils.copyProperties(request, param);
        param.setDeleteFlag(0);
        return RestResult.success(service.listPageBySelective(param, request.getPageNum(), request.getPageSize()));
    }

    @PostMapping("/listPagefreeze")
    @ApiOperation(value = " 分页查询冻结列表 ")
    @ResponseBody
    public RestResult<PageInfo<ConfActivityRule>> listPagefreeze(@RequestBody ConfActivityRuleRequest request) throws Throwable {
        ConfActivityRule param = new ConfActivityRule();
        BeanUtils.copyProperties(request, param);
        param.setDeleteFlag(0);
        return RestResult.success(service.listPageBySelectivefreeze(param, request.getPageNum(), request.getPageSize()));
    }


    /**
     * CONF_ACTIVITY_RULE 查询列表（不分页）
     *
     * @param request 前端请求参数
     */
    @PostMapping("/listAll")
    @ApiOperation(value = "不分页查询 [活动规则主表] ")
    @ResponseBody
    public RestResult<List<ConfActivityRuleResponse>> listConfActivityRuleAllRecord(@RequestBody ConfActivityRuleRequest request) throws Throwable {
        ConfActivityRule param = new ConfActivityRule();
        BeanUtils.copyProperties(request, param);
        param.setDeleteFlag(0);
        List<ConfActivityRule> list = service.listAllRecord(param);
        List<ConfActivityRuleResponse> responseList = list.stream().map(temp -> {
            ConfActivityRuleResponse bo = new ConfActivityRuleResponse();
            BeanUtils.copyProperties(temp, bo);
            return bo;
        }).filter(item -> item != null).collect(Collectors.toList());
        return RestResult.success(responseList);
    }

    /**
     * 冻结申请&&解冻申请
     */
    @PostMapping("/freezeApplication")
    @ResponseBody
    public RestResult<Long> freezeApplication(@Validated @RequestBody ConfActivityRuleRequest request) throws Throwable {
        //根据id查询到信息
        ConfActivityRule confActivityRule = new ConfActivityRule();
        BeanUtils.copyProperties(request, confActivityRule);
        ConfActivityRule result = service.getByPrimaryKey(confActivityRule);
        //主表逻辑删除为1
        service.deleteByPrimaryKeyLogically(confActivityRule);
        //赋值
        result.setSts(request.getSts());
        result.setApplyReason(request.getApplyReason());
        result.setApplierId(request.getAdminOperate().getOperator());
        //插入到申请表
        ConfActivityRuleApply confActivityRuleApply = new ConfActivityRuleApply();
        BeanUtils.copyProperties(result, confActivityRuleApply);
        long flag = confActivityRuleApplyService.insertSelective(confActivityRuleApply);
        return RestResult.success(flag);
    }

    /**
     * 延期提交
     */
    @PostMapping("/delayApply")
    @ResponseBody
    public RestResult<Long> delayApply(@Validated @RequestBody ConfThirdPartRequest request) throws Throwable {
        //根据id查询到信息
        ConfActivityRule confActivityRule = new ConfActivityRule();
        BeanUtils.copyProperties(request, confActivityRule);
        ConfActivityRule result = service.getByPrimaryKey(confActivityRule);
        //主表逻辑删除为1
        service.deleteByPrimaryKeyLogically(confActivityRule);
        //赋值
        result.setEndTime(request.getEndTime());
        result.setApplyReason(request.getApplyReason());
        result.setApplierId(request.getAdminOperate().getOperator());
        //插入到申请表
        ConfActivityRuleApply confActivityRuleApply = new ConfActivityRuleApply();
        BeanUtils.copyProperties(result, confActivityRuleApply);
        long flag = confActivityRuleApplyService.insertSelective(confActivityRuleApply);
        return RestResult.success(flag);
    }

    /**
     * 提前提交
     */
    @PostMapping("/advanceApply")
    @ResponseBody
    public RestResult<Long> advanceApply(@Validated @RequestBody ConfThirdPartRequest request) throws Throwable {
        //根据id查询到信息
        ConfActivityRule confActivityRule = new ConfActivityRule();
        BeanUtils.copyProperties(request, confActivityRule);
        ConfActivityRule result = service.getByPrimaryKey(confActivityRule);
        //主表逻辑删除为1
        service.deleteByPrimaryKeyLogically(confActivityRule);
        //赋值
        result.setEndTime(request.getEndTime());
        result.setApplyReason(request.getApplyReason());
        result.setApplierId(request.getAdminOperate().getOperator());
        //插入到申请表
        ConfActivityRuleApply confActivityRuleApply = new ConfActivityRuleApply();
        BeanUtils.copyProperties(result, confActivityRuleApply);
        long flag = confActivityRuleApplyService.insertSelective(confActivityRuleApply);
        return RestResult.success(flag);
    }

}

	
